package com.neusoft.neuiotms.dcam.fixed.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.constant.AHConstants;
import com.neusoft.neuiotms.dcam.anhui.util.PermUtils;
import com.neusoft.neuiotms.dcam.common.model.Location;
import com.neusoft.neuiotms.dcam.common.repository.LocationRepository;
import com.neusoft.neuiotms.dcam.fixed.asynchronous.AsyncCallService;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetDTO;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.fixed.service.MachinePartsBindService;
import com.neusoft.neuiotms.dcam.fixed.util.AhHelper;
import com.neusoft.neuiotms.dcam.util.CreateLogMessage;
import com.neusoft.neuiotms.dcam.util.OperationEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "资产管理")
@RestController
@RequestMapping(value = "/api/w/fixedAsset")
@Slf4j
public class AssetController {

    @Autowired
    private AssetService assetService;
    @Autowired
    private AsyncCallService asyncCallService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private LocationRepository locationRepository;
    @Autowired
    private MachinePartsBindService machinePartsBindService;
    @Autowired
    private CreateLogMessage createLogMessage;

    @ApiOperation("查询所有安徽固定资产")
    @GetMapping
    public ResultListDTO<AssetDTO> index(final Searchable searchable) {
        final List<AssetDTO> DTOs = this.assetService.index(searchable);
        final ResultListDTO<AssetDTO> result = ResultListDTO.success(DTOs);
        return result;
    }

    @ApiOperation("查询所有安徽固定资产数量")
    @GetMapping("/count")
    public ResultDTO<?> count(final Searchable searchable) {
        final long count = this.assetService.count(searchable);
        return ResultDTO.success(count);
    }

    @ApiOperation("分页查询所有安徽固定资产")
    @GetMapping("/p")
    public PageResultDTO<AssetDTO> search(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.assetService.search(pageable, searchable, userBean));
    }

    @ApiOperation("分页查询已绑定的资产和机器配件")
    @GetMapping("/p/bind")
    public PageResultDTO<AssetDTO> searchBind(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.assetService.searchBind(pageable, searchable, userBean));
    }

    @ApiOperation("分页查询未绑定的资产和机器配件")
    @GetMapping("/p/nobind")
    public PageResultDTO<AssetDTO> searchNoBind(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.assetService.searchNoBind(pageable, searchable, userBean));
    }

    @ApiOperation("保存绑定的资产和机器配件")
    @GetMapping("/saveBind")
    public ResultDTO<Void> saveBind(final Searchable searchable) {
        this.machinePartsBindService.saveBind(searchable);
        return ResultDTO.success();
    }

    @ApiOperation("解除绑定资产和配件")
    @DeleteMapping("deleteBind")
    public ResultDTO<Void> deleteBind(final Searchable searchable) {
        this.machinePartsBindService.deleteBind(searchable);
        return ResultDTO.success();
    }

    @ApiOperation("分页查询我的固定资产")
    @GetMapping("me/p")
    public PageResultDTO<AssetDTO> mySearch(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.assetService.mySearch(pageable, searchable, userBean));
    }

    @ApiOperation("创建安徽固定资产")
    @PostMapping
    public ResultDTO<AssetDTO> create(@RequestBody final AssetDTO dto, final HttpServletRequest request,
            UserBean user) {
        final AssetDTO result = this.assetService.create(dto, request, user);
        return ResultDTO.success(result);
    }

    @ApiOperation("修改安徽固定资产")
    @PutMapping("/{id}")
    public ResultDTO<AssetDTO> update(@PathVariable final Long id,
            @RequestBody final AssetDTO dto, final HttpServletRequest request, UserBean user) {
        final AssetDTO result = this.assetService.update(id, dto);
        if (AhHelper.isSl(result.getBelongs())) {
            this.createLogMessage.sendMsgToLogServer(user, request, OperationEnum.UPDATE.toString(),
                    "资产编码：" + result.getCode());
        }
        return ResultDTO.success(result);
    }

    @ApiOperation("安徽固定资产详情")
    @GetMapping("/{id}")
    public ResultDTO<AssetDTO> details(@PathVariable final Long id) {
        final AssetDTO dto = this.assetService.details(id);
        return ResultDTO.success(dto);
    }

    @ApiOperation("安徽固定资产详情")
    @GetMapping("/code/{code}")
    public ResultDTO<AssetDTO> detailsByCode(@PathVariable final String code) {
        final AssetDTO dto = this.assetService.detailsByCode(code);
        return ResultDTO.success(dto);
    }

    @ApiOperation("删除安徽固定资产")
    @DeleteMapping("/{id}")
    public ResultDTO<Void> delete(@PathVariable final Long id, final HttpServletRequest request, UserBean user) {
        this.assetService.delete(id, request, user);
        return ResultDTO.success();
    }

    @ApiOperation("批量删除安徽固定资产")
    @DeleteMapping("batch/{ids}")
    public ResultDTO<Void> batchDelete(@PathVariable final List<Long> ids) {
        this.assetService.batchDelete(ids);
        return ResultDTO.success();
    }

    @ApiOperation("下载模板")
    @GetMapping("/template/{belongs}")
    public void template(final HttpServletResponse response, @PathVariable final String belongs) {
        final Workbook workbook = this.assetService.template(belongs);
        if (workbook == null) {
            AssetController.log.error("模板导出失败");
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("资产导入模板" + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            AssetController.log.error("下载模板失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                AssetController.log.error("下载模板关闭输出流失败", e);
            }
        }
    }

    @ApiOperation("导入资产")
    @PostMapping("/{belongs}/{categories}/import")
    public void upload(@RequestParam("file") final MultipartFile file, @PathVariable final String categories,
            @PathVariable final String belongs,
            final UserBean userBean, final HttpServletRequest request) {
        try {
            final InputStream fileStream = file.getInputStream();
            final Callable<String> callable = () -> {
                if (fileStream != null) {
                    AssetController.this.assetService.upload(fileStream, belongs, categories,
                            userBean.getUsername());
                }
                return null;
            };
            this.asyncCallService.handle(callable);

            if (AhHelper.isSl(belongs)) {
                this.createLogMessage.sendMsgToLogServer(userBean, request, OperationEnum.IMPORT.toString(),
                        "导入" + AhHelper.translateCategoryName(categories));
            }
        } catch (final IOException e) {
            AssetController.log.error(e.getMessage(), e);
        }
    }

    @ApiOperation("导出资产")
    @GetMapping(value = "/{belongs}/{categories}/{id}/export")
    public void download(final Searchable searchable, final Pageable pageable,
            final HttpServletResponse response, @PathVariable final String categories,
            @PathVariable final String belongs, @PathVariable final String id, final UserBean userBean) {
        // 科技公司-资产管理员查询所有科技的资产，多角色的情况下，资产管理员权限最大
        if (PermUtils.isKJAssetAdmin(userBean)) {
            searchable.put("belongs", AHConstants.BELONG_KJ_CODE);
        }
        // 总行-资产归口管理员和资产归口负责人查询所有总行的资产，多角色的情况下，产归口管理员和资产归口负责人权限最大
        else if (PermUtils.isSLAssetOwnerAdmin(userBean) || PermUtils.isSLAssetOwnerPrincipal(userBean)) {
            searchable.put("belongs", AHConstants.BELONG_SL_CODE);
        } else if (PermUtils.isKJDeptAssetAdmin(userBean) || PermUtils.isKJDeptPrincipal(userBean)
                || PermUtils.isSLDeptAssetAdmin(userBean) || PermUtils.isSLDeptAssetPrincipal(userBean)) {
            final List<String> orgCodeList = userBean.getOrgs();
            searchable.put("managementOrgCode", orgCodeList.toArray(new String[orgCodeList.size()]));
        } else if (PermUtils.isOnlyKJSystemUser(userBean)) {
            searchable.put("managementUserCode", userBean.getUsername());
        }
        final Workbook workbook = this.assetService.export(searchable, pageable, belongs, categories, id);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("资产导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            AssetController.log.error("资产导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                AssetController.log.error("资产导出关闭流失败", e);
            }
        }
    }

    /**
     * 消耗品模板暂不区分总行和科技公司，预留以防万一
     *
     * @param response
     * @param belongs
     */
    @ApiOperation("下载消耗品模板")
    @GetMapping("/xh/template/{belongs}")
    public void xhTemplate(final HttpServletResponse response, @PathVariable final String belongs) {
        final Workbook workbook = this.assetService.xhTemplate(belongs);
        if (workbook == null) {
            AssetController.log.error("消耗品模板导出失败");
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("资产导入模板" + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            AssetController.log.error("下载模板失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                AssetController.log.error("下载模板关闭输出流失败", e);
            }
        }
    }

    @ApiOperation("导出消耗品")
    @GetMapping(value = "/xh/{belongs}/{categories}/{id}/export")
    public void xhDownload(final Searchable searchable, final Pageable pageable,
            final HttpServletResponse response, @PathVariable final String categories, @PathVariable final String id,
            @PathVariable final String belongs) {

        final Workbook workbook = this.assetService.xhExport(searchable, pageable, belongs, categories, id);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("资产导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            AssetController.log.error("资产导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                AssetController.log.error("资产导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("导入消耗品")
    @PostMapping("/xh/{belongs}/{categories}/import")
    public void xhUpload(@RequestParam("file") final MultipartFile file, @PathVariable final String categories,
            @PathVariable final String belongs,
            final UserBean userBean, final HttpServletRequest request) {
        try {
            final InputStream fileStream = file.getInputStream();
            final Callable<String> callable = () -> {
                if (fileStream != null) {
                    AssetController.this.assetService.xhUpload(fileStream, belongs, categories,
                            userBean.getUsername());
                }
                return null;
            };
            this.asyncCallService.handle(callable);
            if (AhHelper.isSl(belongs)) {
                this.createLogMessage.sendMsgToLogServer(userBean, request, OperationEnum.IMPORT.toString(),
                        "导入" + AhHelper.translateCategoryName(categories));
            }
        } catch (final IOException e) {
            AssetController.log.error(e.getMessage(), e);
        }
    }

    @ApiOperation("资产数量统计")
    @GetMapping("/stats/total")
    public ResultDTO<?> assetTotalStats(final Searchable searchable, final UserBean userBean) {
        final Long result = this.assetService.assetTotalStats(searchable, userBean);
        return ResultDTO.success(result);
    }

    @ApiOperation("查询固定资产生命周期")
    @GetMapping("life/{code}")
    public ResultListDTO<AssetLifeCycleDTO> lifeSearch(@PathVariable final String code, final UserBean user) {
        return ResultListDTO.success(this.assetLifeCycleService.detailByCode(code, user));
    }

    @ApiOperation("总价值")
    @GetMapping("/stats/money")
    public ResultDTO<?> assetMoneyStats(final Searchable searchable) {
        final Double result = this.assetRepository.totalMoney(searchable.getStrValue("belongs"),
                Stream.of(searchable.getStrArray("categories")).collect(Collectors.toList()));

        final BigDecimal b = new BigDecimal(null == result ? 0 : result);
        final String f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        return ResultDTO.success(f1);
    }

    @ApiOperation("按资产大分类统计")
    @GetMapping("/statsByBigType/{belongs}")
    public ResultListDTO<?> statsByBigType(@PathVariable final String belongs) {
        final List<Map<String, Object>> list = this.assetRepository.statsByBigType(belongs);
        return ResultListDTO.success(list);
    }

    @ApiOperation("按资产中分类统计")
    @GetMapping("/statsByMiddleType/{belongs}")
    public ResultListDTO<?> statsByMiddleType(@PathVariable final String belongs,
            @RequestParam(name = "bigTypeName", required = false) final String bigTypeName) {
        if (StringUtils.isEmpty(bigTypeName)) {
            final List<Map<String, Object>> list = this.assetRepository.statsByMiddleType(belongs);
            return ResultListDTO.success(list);
        } else {
            final List<Map<String, Object>> list =
                    this.assetRepository.statsByMiddleTypeAndBigType(belongs, bigTypeName);
            return ResultListDTO.success(list);
        }

    }

    //    @ApiOperation("按资产中分类统计")
    //    @GetMapping("/statsByMiddleType/{belongs}/")
    //    public ResultListDTO<?> statsByMiddleTypeAndBig(@PathVariable final String belongs,
    //            @RequestParam(name = "bigTypeName") String bigTypeName) {
    //        final List<Map<String, Object>> list = this.assetRepository.statsByMiddleTypeAndBigType(belongs, bigTypeName);
    //        return ResultListDTO.success(list);
    //    }

    @ApiOperation("按使用部门统计")
    @GetMapping("/statsByOg/{belongs}")
    public ResultListDTO<?> statsByOg(@PathVariable final String belongs) {
        final List<Map<String, Object>> list = this.assetRepository.statsByOg(belongs);
        return ResultListDTO.success(list);
    }

    @ApiOperation("按资产状态统计")
    @GetMapping("/statsByStatus/{belongs}")
    public ResultListDTO<?> statsByStatus(@PathVariable final String belongs) {
        final List<Map<String, Object>> list = this.assetRepository.statsByStatus(belongs);
        return ResultListDTO.success(list);
    }

    @ApiOperation("按库存分类统计")
    @GetMapping("/statsByStorehouse/{belongs}")
    public ResultListDTO<?> statsByStorehouse(@PathVariable final String belongs) {
        final List<String> locationCodeArray = Lists.newArrayList();
        final Location kjRoot = this.locationRepository.findByCode("kj");
        locationCodeArray.add(kjRoot.getCode());

        this.addLocation(locationCodeArray, kjRoot);

        final List<Map<String, Object>> list = this.assetRepository.statsByStorehouse(locationCodeArray);
        return ResultListDTO.success(list);
    }

    @ApiOperation("获取用户角色")
    @GetMapping("/user/role")
    public ResultDTO<?> userRole(final UserBean user) {
        final Map<String, Object> retMap = this.assetService.userRole(user);
        return ResultDTO.success(retMap);
    }

    private void addLocation(final List<String> locationCodeArray, final Location parent) {
        final List<Location> children = this.locationRepository.findByParentCode(parent.getCode());
        for (final Location child : children) {
            locationCodeArray.add(child.getCode());
            this.addLocation(locationCodeArray, child);
        }
    }

    @ApiOperation("导出")
    @GetMapping("/test/{belongs}/{categories}/export")
    public void export(final Searchable searchable, final HttpServletResponse response,
            @PathVariable final String categories,
            @PathVariable final String belongs, final UserBean user) {
        final Workbook workbook = this.assetService.exportWorkbook(searchable, belongs, categories, user);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("资产导出" + LocalDateTime.now() + ".xls", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            AssetController.log.error("资产导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                AssetController.log.error("资产导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("定制导出")
    @GetMapping("/test/{belongs}/{categories}/{ids}/export")
    public void chooseExport(final Searchable searchable, final HttpServletResponse response,
            @PathVariable final String categories,
            @PathVariable final String belongs, final UserBean user) {
        final Workbook workbook = this.assetService.exportWorkbook(searchable, belongs, categories, user);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("资产导出" + LocalDateTime.now() + ".xls", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            AssetController.log.error("资产导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                AssetController.log.error("资产导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("批量标记资产RFID标签已打印过")
    @PutMapping("/label/print")
    public ResultDTO<Void> markLabelPrinted(@RequestBody final List<Long> assetIdList) {
        this.assetService.markLabelPrinted(assetIdList);
        return ResultDTO.success();
    }

    @ApiOperation("按资产大类统计状态、金额和数量")
    @GetMapping("/statsByBigTypeAndStatus/{belongs}")
    public JSONArray statsByBigTypeAndStatus(@PathVariable final String belongs) {

        final List<Map<String, Object>> list = this.assetRepository.statsByBigTypeAndStatus(belongs);

        Lists.newArrayList("1", "2", "3").forEach(categories -> {
            if (list.stream().filter(it -> categories.equals(it.get("categories"))).count() == 0) {
                final Map<String, Object> map = Maps.newHashMap();
                map.put("categories", categories);
                map.put("syCount", "0");
                map.put("xzCount", "0");
                map.put("kcCount", "0");
                map.put("dbfCount", "0");
                map.put("scrapCount", "0");
                map.put("transferCount", "0");
                map.put("unmaintenanceCount", "0");
                map.put("borrowCount", "0");

                list.add(map);
            }
        });

        // 拼装显示数据
        final JSONArray barArray = new JSONArray();
        //        final String[] statusArray = {"使用", "闲置", "库存", "待报废" };
        final List<String> title = new ArrayList<>();
        title.add("资产状态");
        title.add("固定资产");
        title.add("低值易耗品");
        title.add("消耗品");
        barArray.add(title);

        final List<String> syDatas = new ArrayList<>();
        syDatas.add("使用");
        final List<String> xzDatas = new ArrayList<>();
        xzDatas.add("闲置");
        final List<String> kcDatas = new ArrayList<>();
        kcDatas.add("库存");
        final List<String> dbfDatas = new ArrayList<>();
        dbfDatas.add("待报废");
        final List<String> scrapDatas = new ArrayList<>();
        scrapDatas.add("已报废");
        final List<String> transferDatas = new ArrayList<>();
        transferDatas.add("转移中");
        final List<String> unmaintenanceDatas = new ArrayList<>();
        unmaintenanceDatas.add("待维修");
        final List<String> borrowDatas = new ArrayList<>();
        borrowDatas.add("借用中");

        for (int i = 0; i < 3; i++) {
            syDatas.add(list.get(i).get("syCount").toString());
            xzDatas.add(list.get(i).get("xzCount").toString());
            kcDatas.add(list.get(i).get("kcCount").toString());
            dbfDatas.add(list.get(i).get("dbfCount").toString());
            scrapDatas.add(list.get(i).get("scrapCount").toString());
            transferDatas.add(list.get(i).get("transferCount").toString());
            unmaintenanceDatas.add(list.get(i).get("unmaintenanceCount").toString());
            borrowDatas.add(list.get(i).get("borrowCount").toString());
        }
        barArray.add(syDatas);
        barArray.add(xzDatas);
        barArray.add(kcDatas);
        barArray.add(dbfDatas);
        barArray.add(scrapDatas);
        barArray.add(transferDatas);
        barArray.add(unmaintenanceDatas);
        barArray.add(borrowDatas);

        return barArray;
    }

    @ApiOperation("按资产中分类统计金额和数量")
    @GetMapping("/statsByMiddleTypeAndStatus/{belongs}")
    public ResultListDTO<?> statsByMiddleTypeAndStatus(@PathVariable final String belongs) {
        final List<Map<String, Object>> list = this.assetRepository.statsByMiddleTypeAndStatus(belongs);
        return ResultListDTO.success(list);
    }

    @ApiOperation("按使用部门和分类统计资产")
    @GetMapping("/statsByOgAndCategories/{belongs}")
    public ResultDTO<?> statsByOgAndCategories(@PathVariable final String belongs) {
        final List<Map<String, Object>> list = this.assetRepository.statsByOgAndCategories(belongs);
        // 拼装柱状图显示数据
        final JSONArray barArray = new JSONArray();
        final List<String> title = new ArrayList<>();
        title.add("部门实物资产");
        title.add("固定资产");
        title.add("低值易耗品");
        title.add("消耗品");
        barArray.add(title);

        list.forEach(e -> {
            final List<String> value = new ArrayList<>();
            value.add(e.get("name").toString());
            value.add(e.get("gdCount").toString());
            value.add(e.get("dzyhCount").toString());
            value.add(e.get("kxpCount").toString());
            //            if (barArray.size() > 5) {
            //                // 只取前5条数据
            //                return;
            //            } else {
            //                barArray.add(value);
            //            }
            barArray.add(value);
        });
        final Map<String, Object> result = new HashMap<>();
        result.put("echarsData", barArray);
        result.put("tableData", list);
        return ResultDTO.success(result);
    }

    @ApiOperation("按使用个人和分类统计资产")
    @GetMapping("/statsByUserAndCategories/{belongs}")
    public ResultDTO<?> statsByUserAndCategories(@PathVariable final String belongs) {
        final List<Map<String, Object>> list = this.assetRepository.statsByUserAndCategories(belongs);
        // 拼装柱状图显示数据
        final JSONArray barArray = new JSONArray();
        final List<String> title = new ArrayList<>();
        title.add("个人实物资产");
        title.add("固定资产");
        title.add("低值易耗品");
        title.add("消耗品");
        barArray.add(title);

        list.forEach(e -> {
            final List<String> value = new ArrayList<>();
            value.add(e.get("name").toString());
            value.add(e.get("gdCount").toString());
            value.add(e.get("dzyhCount").toString());
            value.add(e.get("kxpCount").toString());
            //            if (barArray.size() > 5) {
            //                // 只取前5条数据
            //                return;
            //            } else {
            //                barArray.add(value);
            //            }
            barArray.add(value);
        });
        final Map<String, Object> result = new HashMap<>();
        result.put("echarsData", barArray);
        result.put("tableData", list);
        return ResultDTO.success(result);
    }

}
